package db.manager;


import java.util.ArrayList;
import java.util.List;

import protocol.meta.Source;
import protocol.meta.Subject;
import protocol.meta.User;
import Utils.SpellUtil;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.provider.BaseColumns;
import android.text.TextUtils;
import app.BaseApplication;

import com.google.gson.Gson;

import db.XoneDBOpenHelper;
import db.XoneDBTables.DiscussTipTable;


public class ManagerDiscussTip {
    public static final int TYPE_BASE = 0;
    // 请求关注好友列表
    public static final int TYPE_USER      = TYPE_BASE;
    // 请求资讯源列表
    public static final int TYPE_SUBSCRIBE = TYPE_BASE + 1;
    // 请求热门话题列表
    public static final int TYPE_TOPIC     = TYPE_BASE + 2;
    // 请求订阅源主题列表
    public static final int TYPE_SUBJECT   = TYPE_BASE + 3;


    public static final int SUBTYPE_BASE = 1;
    // 请求参数类型1 为字符串
    public static final int SUBTYPE_1 = SUBTYPE_BASE;
    // 请求参数类型2，为对象
    public static final int SUBTYPE_2 = SUBTYPE_BASE + 1;
    // 请求参数类型3 为自定义
    public static final int SUBTYPE_3 = SUBTYPE_BASE + 2;

    public static String[] Projection = new String[] {
        BaseColumns._ID,              // 0
        DiscussTipTable.C_TYPE,       // 1
        DiscussTipTable.C_SUBTYPE,    // 2
        DiscussTipTable.C_TIME,       // 3
        DiscussTipTable.C_PINYIN,     // 4
        DiscussTipTable.C_CONTENT,    // 5
        DiscussTipTable.C_JSON        // 6
    };

    public static final int ID        = 0;
    public static final int TYPE      = 1;
    public static final int SUBTYPE   = 2;
    public static final int TIME      = 3;
    public static final int PINYIN    = 4;
    public static final int CONTENT   = 5;
    public static final int JSON      = 6;

    private static Context mContext = BaseApplication.getAppInstance().getApplicationContext();

    private static final String[] CHARACTER_ARRAY = {"@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
        "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    public static void insertTest() {
        List<User> list = null;
        User user = null;

        list = new ArrayList<User>();
        for (int i = 0; i < CHARACTER_ARRAY.length; i++) {
        	
        	user = new User();
            user.nickname = "z关注用户" + 1;
            user.avatar = "http://bg.9u.com/uploads/allimg/121208/1FA36240-1.jpg";
            user.signature = "内容测试" + 1;
            list.add(user);
            
            user = new User();
            user.nickname = CHARACTER_ARRAY[i] + "关注用户" + 1;
            user.avatar = "http://bg.9u.com/uploads/allimg/121208/1FA36240-1.jpg";
            user.signature = "内容测试" + 1;
            list.add(user);

            user = new User();
            user.nickname = CHARACTER_ARRAY[i] + "关注用户" + 2;
            user.avatar = "http://bg.9u.com/uploads/allimg/121208/1FA36240-1.jpg";
            user.signature = "内容测试" + 2;
            list.add(user);
        }

        ManagerDiscussTip.replaceUser(list, false);

        List<Source> list2 = null;
        Source subscribe = null;

        list2 = new ArrayList<Source>();
        for (int i = 0; i < CHARACTER_ARRAY.length; i++) {
            subscribe = new Source(null);
            subscribe.sourceName = CHARACTER_ARRAY[i] + "订阅资讯源" + 1;
            subscribe.avatar = "http://bg.9u.com/uploads/allimg/121208/1FA36240-1.jpg";
            subscribe.desc = "内容测试" + 1;
            list2.add(subscribe);

            subscribe = new Source(null);
            subscribe.sourceName = CHARACTER_ARRAY[i] + "订阅资讯源" + 2;
            subscribe.avatar = "http://bg.9u.com/uploads/allimg/121208/1FA36240-1.jpg";
            subscribe.desc = "内容测试" + 2;
            list2.add(subscribe);
        }

        ManagerDiscussTip.replaceSource(list2, false);

        String value = null;
        List<String> list1 = null;
        list1 = new ArrayList<String>();
        for (int i = 0; i < CHARACTER_ARRAY.length; i++) {
            value = "热门话题" + i;
            list1.add(value);
        }
        ManagerDiscussTip.replaceTopic(list1);

        List<Subject> list3 = null;
        Subject subject = null;

        list3 = new ArrayList<Subject>();
        for (int i = 0; i < CHARACTER_ARRAY.length; i++) {
            subject = new Subject(null);
            subject.subjectName = CHARACTER_ARRAY[i] + "订阅主题" + 1;
            subject.avatar = "http://bg.9u.com/uploads/allimg/121208/1FA36240-1.jpg";
            list3.add(subject);

            subject = new Subject(null);
            subject.subjectName = CHARACTER_ARRAY[i] + "订阅主题" + 2;
            subject.avatar = "http://bg.9u.com/uploads/allimg/121208/1FA36240-1.jpg";
            list3.add(subject);
        }

        ManagerDiscussTip.replaceSubject(list3, false);
    }

    /**
     * 删除所有信息
     */
    public static void deleteAll() {
        mContext.getContentResolver().delete(DiscussTipTable.CONTENT_URI, null, null);
    }

    public static void deletByType(int type) {
    	String where = DiscussTipTable.C_TYPE + "=?";
    	 String[] selectionArgs = new String[]{String.valueOf(type)};
    	 mContext.getContentResolver().delete(DiscussTipTable.CONTENT_URI, where, selectionArgs);
    }
    
    public static void deletByType(int type, int subType) {
        String where = DiscussTipTable.C_TYPE + "=? AND " + DiscussTipTable.C_SUBTYPE + "=?";
         String[] selectionArgs = new String[]{String.valueOf(type), String.valueOf(subType)};
         mContext.getContentResolver().delete(DiscussTipTable.CONTENT_URI, where, selectionArgs);
    }
    
    /**
     * 批量插入用户信息,如果是服务器新获取的要删除老信息。
     * @param list
     * @param bAt true,最近@; false,服务器新取的。
     */
    public static void replaceUser(List<User> list, boolean bAt) {
        if (null == list || 0 == list.size()) {
            return;
        }
        
        if (!bAt) {
            deletByType(TYPE_USER, SUBTYPE_2);
        }
        
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT OR REPLACE INTO ");

        sql.append(DiscussTipTable.TABLE_NAME);
        sql.append("(");

        sql.append(DiscussTipTable.C_TYPE);     // 1
        sql.append(",");
        sql.append(DiscussTipTable.C_SUBTYPE);  // 2
        sql.append(",");
        sql.append(DiscussTipTable.C_TIME);     // 3
        sql.append(",");
        sql.append(DiscussTipTable.C_PINYIN);   // 4
        sql.append(",");
        sql.append(DiscussTipTable.C_CONTENT);  // 5
        sql.append(",");
        sql.append(DiscussTipTable.C_JSON);     // 6

        sql.append(")");
        sql.append(" VALUES(");
        sql.append("?,?,?,?,?,?");
        sql.append(");");

        SQLiteDatabase database = null;
        SQLiteStatement statement = null;
        try {
            SQLiteOpenHelper openHelper = XoneDBOpenHelper.getInstance(mContext);
            database = openHelper.getWritableDatabase();
            database.beginTransaction();
            statement = database.compileStatement(sql.toString());
            Gson gson = new Gson();
            for (User entity : list) {
                statement.bindLong(1, TYPE_USER);
                statement.bindLong(3, System.currentTimeMillis());
                if (bAt) {
                    statement.bindLong(2, SUBTYPE_3);
                    bindString(statement, 4, "@");
                    bindString(statement, 5, entity.nickname + " ");
                } else {
                    statement.bindLong(2, SUBTYPE_2);
                    bindString(statement, 4, SpellUtil.converterToFirstSpell(entity.nickname));
                    bindString(statement, 5, entity.nickname);
                }
                bindString(statement, 6, gson.toJson(entity));
                statement.execute();
            }
            mContext.getContentResolver().notifyChange(DiscussTipTable.CONTENT_URI, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != statement) {
                statement.close();
            }

            if (null != database) {
                database.setTransactionSuccessful();
                database.endTransaction();
            }
        }
    }

    /**
     * 批量插入用户信息
     * @param list
     */
    public static void replaceSource(List<Source> list, boolean bAt) {
        if (null == list || 0 == list.size()) {
            return;
        }

        if (!bAt) {
            deletByType(TYPE_SUBSCRIBE, SUBTYPE_2);
        }
        
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT OR REPLACE INTO ");

        sql.append(DiscussTipTable.TABLE_NAME);
        sql.append("(");

        sql.append(DiscussTipTable.C_TYPE);     // 1
        sql.append(",");
        sql.append(DiscussTipTable.C_SUBTYPE);  // 2
        sql.append(",");
        sql.append(DiscussTipTable.C_TIME);     // 3
        sql.append(",");
        sql.append(DiscussTipTable.C_PINYIN);   // 4
        sql.append(",");
        sql.append(DiscussTipTable.C_CONTENT);  // 5
        sql.append(",");
        sql.append(DiscussTipTable.C_JSON);     // 6

        sql.append(")");
        sql.append(" VALUES(");
        sql.append("?,?,?,?,?,?");
        sql.append(");");

        SQLiteDatabase database = null;
        SQLiteStatement statement = null;
        try {
            SQLiteOpenHelper openHelper = XoneDBOpenHelper.getInstance(mContext);
            database = openHelper.getWritableDatabase();
            database.beginTransaction();
            statement = database.compileStatement(sql.toString());
            Gson gson = new Gson();
            for (Source entity : list) {
                statement.bindLong(1, TYPE_SUBSCRIBE);
                statement.bindLong(2, SUBTYPE_2);
                statement.bindLong(3, System.currentTimeMillis());
                if (bAt) {
                    statement.bindLong(2, SUBTYPE_3);
                    bindString(statement, 4, "@");
                    bindString(statement, 5, entity.sourceName + " ");
                } else {
                    statement.bindLong(2, SUBTYPE_2);
                    bindString(statement, 4, SpellUtil.converterToFirstSpell(entity.sourceName));
                    bindString(statement, 5, entity.sourceName);
                }
                
                bindString(statement, 6, gson.toJson(entity));
                statement.execute();
            }
            mContext.getContentResolver().notifyChange(DiscussTipTable.CONTENT_URI, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != statement) {
                statement.close();
            }

            if (null != database) {
                database.setTransactionSuccessful();
                database.endTransaction();
            }
        }
    }

    /**
     * 批量插入订阅主题
     * @param list
     */
    public static void replaceSubject(List<Subject> list, boolean bAt) {
        if (null == list || 0 == list.size()) {
            return;
        }

        if (!bAt) {
            deletByType(TYPE_SUBJECT, SUBTYPE_2);
        }
        
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT OR REPLACE INTO ");

        sql.append(DiscussTipTable.TABLE_NAME);
        sql.append("(");

        sql.append(DiscussTipTable.C_TYPE);     // 1
        sql.append(",");
        sql.append(DiscussTipTable.C_SUBTYPE);  // 2
        sql.append(",");
        sql.append(DiscussTipTable.C_TIME);     // 3
        sql.append(",");
        sql.append(DiscussTipTable.C_PINYIN);   // 4
        sql.append(",");
        sql.append(DiscussTipTable.C_CONTENT);  // 5
        sql.append(",");
        sql.append(DiscussTipTable.C_JSON);     // 6

        sql.append(")");
        sql.append(" VALUES(");
        sql.append("?,?,?,?,?,?");
        sql.append(");");

        SQLiteDatabase database = null;
        SQLiteStatement statement = null;
        try {
            SQLiteOpenHelper openHelper = XoneDBOpenHelper.getInstance(mContext);
            database = openHelper.getWritableDatabase();
            database.beginTransaction();
            statement = database.compileStatement(sql.toString());
            Gson gson = new Gson();
            for (Subject entity : list) {
                statement.bindLong(1, TYPE_SUBJECT);
                statement.bindLong(3, System.currentTimeMillis());
                if (bAt) {
                    statement.bindLong(2, SUBTYPE_3);
                    bindString(statement, 4, "@");
                    bindString(statement, 5, entity.subjectName + " ");
                } else {
                    if (TextUtils.isDigitsOnly(SpellUtil.converterToFirstSpell(entity.subjectName))) {
                        statement.bindLong(2, SUBTYPE_2);
                        bindString(statement, 4, "@");
                        bindString(statement, 5, entity.subjectName);
                    } else {
                        statement.bindLong(2, SUBTYPE_2);
                        bindString(statement, 4, SpellUtil.converterToFirstSpell(entity.subjectName));
                        bindString(statement, 5, entity.subjectName);
                    }
                   
                }
                bindString(statement, 6, gson.toJson(entity));
                statement.execute();
            }
            mContext.getContentResolver().notifyChange(DiscussTipTable.CONTENT_URI, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != statement) {
                statement.close();
            }

            if (null != database) {
                database.setTransactionSuccessful();
                database.endTransaction();
            }
        }
    }

    /**
     * 批量插入用户信息, 资讯源，热门话题
     * @param list
     * @param type
     */
    public static void replaceTopic(List<String> list) {
        if (null == list || 0 == list.size()) {
            return;
        }

        deletByType(TYPE_TOPIC);
        
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT OR REPLACE INTO ");

        sql.append(DiscussTipTable.TABLE_NAME);
        sql.append("(");

        sql.append(DiscussTipTable.C_TYPE);     // 1
        sql.append(",");
        sql.append(DiscussTipTable.C_SUBTYPE);  // 2
        sql.append(",");
        sql.append(DiscussTipTable.C_TIME);     // 3
        sql.append(",");
        sql.append(DiscussTipTable.C_PINYIN);   // 4
        sql.append(",");
        sql.append(DiscussTipTable.C_CONTENT);  // 5

        sql.append(")");
        sql.append(" VALUES(");
        sql.append("?,?,?,?,?");
        sql.append(");");

        SQLiteDatabase database = null;
        SQLiteStatement statement = null;
        try {
            SQLiteOpenHelper openHelper = XoneDBOpenHelper.getInstance(mContext);
            database = openHelper.getWritableDatabase();
            database.beginTransaction();
            statement = database.compileStatement(sql.toString());
            for (String entity : list) {
                statement.bindLong(1, TYPE_TOPIC);
                statement.bindLong(2, SUBTYPE_1);
                statement.bindLong(3, System.currentTimeMillis());
                bindString(statement, 4, SpellUtil.converterToFirstSpell(entity));
                bindString(statement, 5, entity);
                statement.execute();
            }
            mContext.getContentResolver().notifyChange(DiscussTipTable.CONTENT_URI, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != statement) {
                statement.close();
            }

            if (null != database) {
                database.setTransactionSuccessful();
                database.endTransaction();
            }
        }
    }

    private static void bindString(SQLiteStatement stat, int index, String value) {
        if (value == null) {
            stat.bindNull(index);
        } else {
            stat.bindString(index, value);
        }
    }
}
